package com.cloudcc.mobile.view.web;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.dao.impl.BeauInfoShareSet;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.activity.BeauListActivity;
import com.cloudcc.mobile.view.activity.CreateMultipleListActivity;
import com.cloudcc.mobile.view.activity.RecordtypeActivity;
import com.cloudcc.mobile.view.base.BaseWebViewFragment;
import com.litesuits.android.log.Log;
import com.mypage.utils.SaveTemporaryData;
import com.mypage.view.activity.beautMore.ChangeRecordActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: webҳ�� ������������� url
 * @author wangzhiqiang
 * @date 2015-12-4 ����11:18:41
 *
 */
public class WebFragment extends BaseWebViewFragment {

	protected static final int STEP_START = 1;
	protected static final int STEP_OVERRIDEURL = 2;
	protected static final int STEP_FINISH = 3;
	private ContentResolver contentResolver;
	private ISyncInterface mISyncInterface;
	private String uri_raw = "content://com.android.contacts/raw_contacts";
	private String uri_phone = "content://com.android.contacts/data/phones";
	private boolean islxr;
	private String isFrom;
	@Override
	public void init() {
		super.init();
		initSync();
		selectData();
//		daoru_lay.setVisibility(View.VISIBLE);

//        int index = getIntent().getIntExtra("page.index", 0);
//        if(cjlxrph!=null||cjlxrna!=null) {
//            daoru_lay.setVisibility(View.VISIBLE);
//        } else {
//            daoru_lay.setVisibility(View.GONE);
//        }
		if(mUrl.contains("obj=003")) {
			daoru_lay.setVisibility(View.GONE);
			android.util.Log.i("murl1", "---------------"+mISyncInterface);

		}else {
			daoru_lay.setVisibility(View.GONE);
		}
		daoru_lian.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

					Uri uri = ContactsContract.Contacts.CONTENT_URI;
					Intent intent = new Intent(Intent.ACTION_PICK, uri);
					startActivityForResult(intent,0);

			}
		});

        daoru_lian_im.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

	}

	private void initSync() {
		Bundle bundle = getArguments();
		if (bundle==null) {
			return;
		}
		mISyncInterface =(ISyncInterface) bundle.getSerializable("callback");
		isFrom = bundle.getString("from");

	}

	@Override
	protected void onPreInitWebView() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			mUrl = bundle.getString(ExtraConstant.EXTRA_URL, "");
			daoruurl=bundle.getString("daoruurl", "");
            cjlxrna = bundle.getString("name","");
            cjlxrph = bundle.getString("phone","");
			form = bundle.getString("form","");
			Log.d("urlwebview", "webviewurl"+mUrl);
			Log.d("---daoruurl", daoruurl+"---");
		}

	}
//
//	protected void initSyncUrl() {
//		mSyncUrls = new ArrayList<SyncParam>();
//		mSyncUrls.add(new SyncParam("m=save", true, STEP_FINISH,new String[]{"m=query","WeiXin_index.action"}));
//		mSyncUrls.add(new SyncParam("wx_taskquery.action?m=query", true, STEP_OVERRIDEURL,new String[]{"m=list"}));
//		mSyncUrls.add(new SyncParam("m=delete", true, STEP_FINISH,new String[]{""}));
//		mSyncUrls.add(new SyncParam("/WeiXin_reassignWorkitem.action", true, STEP_FINISH,new String[]{"WeiXin_index.action"}));
//		mSyncUrls.add(new SyncParam("/WeiXin_processApproval.action", true, STEP_FINISH,new String[]{"WeiXin_index.action","weixin_index.action"}));
//	}

	@Override
	public WebViewClient getWebViewClient() {
		return new SyncWebClient();
	}

	private class SyncWebClient extends BaseWebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			if (mISyncInterface!=null) {
				Log.d("webfragmentxinjian", "��ʼ����");
				mISyncInterface.onPageStarted(view, url);
			}
		}
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			if (mISyncInterface!=null) {
				Log.d("webfragmentxinjian", "��ʼ���ؽ���");

				mISyncInterface.onPageFinished(view, url);
			}
//			 mWebView.loadUrl("javascript:$(function(){$('.le-title').css('font-size','18px');$('.le-title').css('margin-top','9px');$('.le-header').css('height','44px');$('.le-header').css('border','0px');$('.header-left').css('top','9px');$('.header-left').hover().css('margin-top','-1.5px');});");
//			 stopProgressDialog();
		}
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			LogUtils.d("webview", "url:" + url);
			if(url.contains("obj=003")) {
				daoru_lay.setVisibility(View.GONE);
				android.util.Log.i("murl1", "---------------"+mISyncInterface);
			}else {
				islxr = false;
			}
			if (mISyncInterface!=null) {
				Log.d("webfragmentxinjian", "�м�1");
				if (UrlManager.isHome(url)) {// ��ҳ
					getActivity().finish();
						if (ChangeRecordActivity.instance != null) {
							BeauInfoShareSet.getInstance().setChangeDao("保存成功");
							ChangeRecordActivity.instance.finish();

						}
					return mISyncInterface.shouldOverrideUrlLoading(view, url);
				}
				if(url.contains("weiquery.action")&&url.contains("m=query")&&"beauinfo".equals(isFrom)){
						BeauInfoShareSet.getInstance().setbeauinfotoast("保存成功");
//                    RunTimeManager.getInstance().setUserName("保存成功");
					getActivity().finish();
					return mISyncInterface.shouldOverrideUrlLoading(view, url);
				}
				if(url.contains("weiquery.action")&&url.contains("m=query")){
						if(mUrl.contains("obj=003") || mUrl.contains("obj=004")) {
							if(RecordtypeActivity.instance != null){
								RecordtypeActivity.instance.finish();
							}
							if ("beauinfo".equals(isFrom)) {
								BeauInfoShareSet.getInstance().setbeauinfotoast("保存成功");
							} else {
								RunTimeManager.getInstance().setUserName(username);
							}
						}


					Bundle bundle = getArguments();
					String ss = bundle.getString("tags");
					if ("cloudcc".equals(bundle.getString("tags"))) {
						getActivity().finish();
						CreateMultipleListActivity.install.finish();
					}
					String tag = bundle.getString("tag");
					if("beizhu".equals(tag)){
						return mISyncInterface.shouldOverrideUrlLoading(view, url);
					}else if("shenpi".equals(tag)){
						return mISyncInterface.shouldOverrideUrlLoading(view, url);
					}else{
						RunTimeManager.getInstance().setIsbaocun(true);
						if(form != null && form.equals("calllog")){
                            Intent intent = new Intent(getActivity(), BeauListActivity.class);
                            if(mUrl.contains("obj=003")){
                                intent.putExtra(ExtraConstant.EXTRA_ID, "contact");
                                intent.putExtra(ExtraConstant.EXTRA_NAME, "联系人");
                                intent.putExtra("imageId", "cloudtab_must_003");
                                intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                                        .getNewRecordUrl("003"));
                            }else if(mUrl.contains("obj=004")){
                                intent.putExtra(ExtraConstant.EXTRA_ID, "lead");
                                intent.putExtra(ExtraConstant.EXTRA_NAME, "潜在客户");
                                intent.putExtra("imageId", "cloudtab_must_004");
                                intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                                        .getNewRecordUrl("004"));
                            }
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
						}
						getActivity().finish();
						return mISyncInterface.shouldOverrideUrlLoading(view, url);
					}
				}else if(url.contains("home_mainPage.action")){
					getActivity().finish();
					return mISyncInterface.shouldOverrideUrlLoading(view, url);
				}else if(url.contains("wx_taskquery.action")&&!(url.contains("m=list"))&&!(url.contains("m=edit"))&&!(url.contains("m=newpage"))){
					getActivity().finish();
					if (ChangeRecordActivity.instance != null) {
						SaveTemporaryData.saveWebView="保存成功";
						ChangeRecordActivity.instance.finish();

					}

					return mISyncInterface.shouldOverrideUrlLoading(view, url);
				}
				return mISyncInterface.shouldOverrideUrlLoading(view, url);
			}else if(url.contains("/weiquery.action?m=query&id=")){
				getActivity().finish();

				return mISyncInterface.shouldOverrideUrlLoading(view, url);
			}else{
				Log.d("webfragmentxinjian", "�м�2");
				return super.shouldOverrideUrlLoading(view, url);

			}
		}
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	//查询联系人数据并放到集合里
	private List<Map<String, String>> selectData() {
		/**
		 * 1.先查询raw 获取_id查出所有联系人
		 * 2.循环查询-->根据_id去data表中（_id=raw_contacts_id）查询 data1数据
		 */
		contentResolver = getActivity().getContentResolver();
		Cursor cursor = contentResolver.query(Uri.parse(uri_raw), new String[]{"_id", "display_name"}, null, null, null);
		//cursor返回的cursor数量不定
		List<Map<String, String>> list = new ArrayList<>();
		if (cursor != null && cursor.moveToNext()) {
			String _id = cursor.getString(0);
			String displayName = cursor.getString(1);
			Map<String, String> map = new HashMap<>();
			map.put("_id", _id);
			map.put("display_Name", displayName);
			//根据_id 去data查手机号
			Cursor cursor1 = contentResolver.query(Uri.parse(uri_phone), new String[]{"data1"}, "raw_contact_id=?", new String[]{_id}, null);
//            Cursor cursor3=contentResolver.query()
			//循环拿到手机号
			StringBuffer sb = new StringBuffer();
			//这里循环拿到手机号是因为有时联系人中 你可能一个人有几个电话
			while (cursor1 != null && cursor1.moveToNext()) {
				sb.append(cursor1.getString(0) + "\n");
			}
			map.put("data1", sb.toString());
			list.add(map);
		}else {
			daoru_lian.setVisibility(View.GONE);
			et_mobile.setVisibility(View.VISIBLE);
		}
		return list;
	}
}
